package com.ops.chirpit;

import java.io.File;
import java.io.IOException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;

import twitter4j.GeoLocation;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.Authorization;
import twitter4j.auth.OAuthAuthorization;
import twitter4j.conf.Configuration;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.media.ImageUpload;
import twitter4j.media.ImageUploadFactory;
import twitter4j.media.MediaProvider;
import android.location.Location;
import android.os.Bundle;
import android.util.Log;

import com.facebook.android.Facebook;

import fi.foyt.foursquare.api.FoursquareApi;
import fi.foyt.foursquare.api.FoursquareApiException;
import fi.foyt.foursquare.api.Result;
import fi.foyt.foursquare.api.entities.Checkin;

public class UpdateHelper {

    public static Boolean updateFoursquare(String token, String status, JSONArray images, Location location, String place, String attachUrl) {
  	  FoursquareApi fsApi = ChirpItActivity.foursquareApi;
  	  fsApi.setoAuthToken(token);
  	  String ll = null; double llAcc = 0; double alt = 0;
  	  if (location != null){
	    	  ll = location.getLatitude() + "," + location.getLongitude();
	    	  llAcc = location.getAccuracy();
	    	  alt = locatiResult<T>Altitude();
  	  }
  	    try {
  	    	Result<Checkin> fsResult = fsApi.checkinsAdd(place, null, status, "public", ll, llAcc, alt, null);
  	    	Checkin fsCheckin = fsResult.getResult();
  	    } catch (FoursquareApiException e) {
  	      // TODO: Error handling
  	    	return false;
  	    }
  	    return true;
	  }
    public static boolean updateFacebook(String id, String token, String status, JSONArray images, Location location, String place, String attachUrl){
    	Facebook authdFacebook = new Facebook(ChirpItActivity.FB_APP_ID);
    	authdFacebook.setAccessToken(token);
    	authdFacebook.setAccessExpiresIn("0");
    	if (!authdFacebook.isSessionValid()) return false;
    	String page = "feed";
        try {
            Bundle parameters = new Bundle();
            JSONObject coordinates = new JSONObject();
            if(ChirpItActivity.attachFriends[ChirpItActivity.FACEBOOK].length() > 0){
            	JSONArray fbFriends = new JSONArray();
            	for(int i = 0; i < ChirpItActivity.attachFriends[ChirpItActivity.FACEBOOK].length(); i++){
	        		JSONObject friend = ((JSONObject) ChirpItActivity.attachFriends[ChirpItActivity.FACEBOOK].get(i));
            		if(friend.getInt("provider")==ChirpItActivity.FACEBOOK){
            			fbFriends.put(friend.getString("id"));
            		}
            	}
            	parameters.putString("tags", fbFriends.toString());
            }
            if (place != null){
            	parameters.putString("place", place);
            	coordinates.put("latitude", location.getLatitude());
            	coordinates.put("longitude", location.getLongitude());
            	parameters.putString("coordinates", coordinates.toString());
            	page = "checkins";
            }else if (attachUrl != null){
            	status = status + " " + attachUrl;
            	parameters.putString("link", attachUrl);
            	parameters.putString("type", "link");
            }else if (!images.isNull(0)){
            	String imageUrl = uploadPicture(authdFacebook, status, images.getString(0));
            	parameters.putString("picture", imageUrl);
            	parameters.putString("type", "picture");
            	return true;
            }
            parameters.putString("message", status);

            String response = authdFacebook.request(id+"/"+page, parameters, 
                    "POST");
            Log.d("Tests", "got response: " + response);
            // TODO: kill authdFacebook
            if (response == null || response.equals("") || 
                    response.equals("false")) {
                return false;
            }
            
            Log.d("Tests", "All Authenticated Tests Passed");
            return true;
        } catch (Throwable e) {
            e.printStackTrace();
            return false;
        }
    }

	private static String uploadPicture(Facebook authdFacebook, String status, String imagePath) throws ParseException, IOException {
    	//Facebook authdFacebook = ChirpItActivity.authenticatedFacebook;
    	if (!authdFacebook.isSessionValid()) return null;
    	String fbToken = authdFacebook.getAccessToken();
    	HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams( ).setParameter( CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1 );

        HttpPost httppost = new HttpPost( "https://graph.facebook.com/me/photos" );
        File file = new File( imagePath );

        // DEBUG
        Log.d( "TEST", "FILE::" + file.exists( ) ); // IT IS NOT NULL
        Log.d( "TEST", "AT:" + fbToken ); // I GOT SOME ACCESS TOKEN

        MultipartEntity mpEntity  = new MultipartEntity( );
        ContentBody cbFile        = new FileBody( file, "image/png" );
        ContentBody cbMessage     = new StringBody( status );
        ContentBody cbAccessToken = new StringBody( fbToken );

        mpEntity.addPart( "access_token", cbAccessToken );
        mpEntity.addPart( "source",       cbFile        );
        mpEntity.addPart( "message",      cbMessage     );        

        httppost.setEntity( mpEntity );

        // DEBUG
        System.out.println( "executing request " + httppost.getRequestLine( ) );
        HttpResponse response = httpclient.execute( httppost );
        HttpEntity resEntity = response.getEntity( );

        // DEBUG
        System.out.println( response.getStatusLine( ) );
        if (resEntity != null) {
          System.out.println( EntityUtils.toString( resEntity ) );
        } // end if

        if (resEntity != null) {
          resEntity.consumeContent( );
        } // end if

        httpclient.getConnectionManager( ).shutdown( );
        return EntityUtils.toString( resEntity );
    } // end of uploadPicture( )

	public static Boolean updateTwitter(String token, String secret, String status, Location location, JSONArray images, String attachPlace, String attachUrl) {
		String message = null;
		String imageUrl = null;
		// initialize Twitter4J
		try{
			Twitter twitter = new TwitterFactory().getInstance();
			AccessToken a = new AccessToken(token, secret);
			String consumerKey = AuthActivity.twConsumerKey, consumerSecret = AuthActivity.twConsumerSecret;
			twitter.setOAuthConsumer(consumerKey, consumerSecret);
			twitter.setOAuthAccessToken(a);
			// create a tweet
	        if(ChirpItActivity.attachFriends[0].length() > 0){
	        	String tags = "";
	        	for(int i = 0; i < ChirpItActivity.attachFriends[0].length(); i++){
	        		JSONObject friend = ((JSONObject) ChirpItActivity.attachFriends[0].get(i));
	        		if(friend.getInt("provider")==ChirpItActivity.TWITTER){
	        			tags += "@"+friend.getString("screenName") + " ";
	        		}
	        	}
	        	status =  tags + status;
	        }
			StatusUpdate statusUpdate = new StatusUpdate(status);
			
			if (!images.isNull(0)){
				String[] args = {"39f52a18b356691f8fd43ea826b3392e",images.getString(0)};
				try {
					Configuration conf = new ConfigurationBuilder().setMediaProviderAPIKey(args[0])
								.setOAuthConsumerKey(consumerKey).setOAuthConsumerSecret(consumerSecret).
									setOAuthAccessToken(a.getToken()).setOAuthAccessTokenSecret(a.getTokenSecret()).build();
									Authorization oauth = new OAuthAuthorization(conf) ;
					ImageUpload upload = new ImageUploadFactory(conf).getInstance(MediaProvider.TWITPIC, oauth);
		            if (args.length >= 3) {
		                imageUrl = upload.upload(new File(args[1]), args[2]);
		            } else {
		                imageUrl = upload.upload(new File(args[1]));
		            }
		            message = "Successfully uploaded image to Twitpic at " + imageUrl;
		        } catch (TwitterException te) {
		            message = "Failed to upload the image: " + te.getMessage();
		        }
				
			}
			if (imageUrl != null)
				statusUpdate = new StatusUpdate(statusUpdate.getStatus() + " " + imageUrl);
	
			if (attachUrl != null)
				statusUpdate = new StatusUpdate(statusUpdate.getStatus() + " " + attachUrl);
			
			if (location != null){
				GeoLocation geoLocation = new GeoLocation(location.getLatitude(), location.getLongitude());
				statusUpdate.location(geoLocation);
				statusUpdate.setPlaceId(attachPlace);
			}
		
		
			// send the tweet
		
			twitter.updateStatus(statusUpdate);
	
		} catch (Exception e) {
			message = e.getMessage();
			return false;
		}
	
		return true;
		
		//return "success";
		
	}
    
}
